package com.nwpu.ex2_2.ShoppingCart;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * BookAddedListener
 *
 * @author 龙虹宇
 * @version 1.0
 * @date 2023/10/14
 */
@WebListener
public class BookAddedListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        // 获取添加的属性名
        String name = httpSessionBindingEvent.getName();
        // 如果name是item1, item2, …或itemCount，则将value输出到终端
        if ("itemCount".equals(name) ||
                (name.startsWith("item") &&
                        Integer.parseInt(name.substring(4)) > 0)) {
            System.out.println();
            System.out.println("监听器：" + name + " : " + httpSessionBindingEvent.getValue() + " >已添加到session");
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        // 获取添加的属性名
        String name = httpSessionBindingEvent.getName();
        // 如果name是itemCount，则将更新信息输出到终端

        /* 注意：如果直接使用getValue会得到旧值
                获得新值替换为getSession().getAttribute(name)
         */
        if ("itemCount".equals(name)) {
            System.out.println();
            System.out.println("监听器：" + name + " >:" +
                    httpSessionBindingEvent.getValue());
        }
    }
}
